package com.dragon.logical.service.supplies.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.common.util.DateNumUtils;
import com.dragon.logical.service.customer.CustomerService;
import com.dragon.logical.service.supplies.IPurchaseRequisitionService;
import com.dragon.logical.service.supplies.IProductService;
import com.dragon.repository.entity.*;
import com.dragon.repository.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 请购单 服务实现类
 * </p>
 *
 * @author sy
 * @since 2023-10-20
 */
@Service
public class PurchaseRequisitionServiceImpl extends ServiceImpl<PurchaseRequisitionMapper, PurchaseRequisition> implements IPurchaseRequisitionService {

    @Autowired
    PurchaseRequisitionMapper purchaseMapper;
    @Autowired
    AdminMapper adminMapper;
    @Autowired
    RequisitionProductMapper requisitionProductMapper;
    @Autowired
    ProcurementMapper procurementMapper;
    @Autowired
    IProductService productService;
    @Autowired
    ProductUnitMapper unitMapper;
    @Autowired
    ProcurementProductMapper procurementProductMapper;
    @Autowired
    ProductMapper productMapper;
    @Autowired
    CustomerService customerService;

    @Override
    public Page<PurchaseRequisition> getPurchaseList(Integer page, Integer limit, Integer id, String search) {
        Page<PurchaseRequisition> prPage = new Page<>(page, limit);
        Page<PurchaseRequisition> requisitionPage = purchaseMapper.selectPurchasePage(prPage, id, search);
        requisitionPage.getRecords().forEach( purchaseRequisition -> {
            String operatorName = adminMapper.selectUsernameById(purchaseRequisition.getOperatorId());
            purchaseRequisition.setOperatorName(operatorName);
            List<RequisitionProduct> requisitionProducts = requisitionProductMapper.selectByRequisitionId(purchaseRequisition.getId(),null);
            purchaseRequisition.setRequisitionProductList(requisitionProducts);
        });
        return requisitionPage;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public AddPageData addPurchase(PurchaseRequisition purchaseRequisition) {
        purchaseRequisition.setCompanyId(1);
        purchaseRequisition.setCreateTime(DateUtil.date());
        //自动生成编号
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String code = "QG-" + sdf.format(purchaseRequisition.getCreateTime());
        String maxCode =  purchaseMapper.maxRoundInoutNumber(code);
        String newCode = null;
        if (StrUtil.isEmpty(maxCode)){
            newCode = code + "001";
        }
        else {
            String getMaxCode = maxCode.substring(11, 14);
            newCode = code + DateNumUtils.getNum(getMaxCode);
        }
        purchaseRequisition.setPurchaseCode(newCode);
        purchaseMapper.insert(purchaseRequisition);
        purchaseRequisition.getRequisitionProductList().forEach(requisitionProduct -> {
            Product product = productMapper.selectById(requisitionProduct.getProductSpuId());
            double BuyPrice = requisitionProduct.getPrice() * requisitionProduct.getProductBuyNum();
            requisitionProduct.setProductBuyPrice(BuyPrice);
            requisitionProduct.setUnitId(product.getProductUnitId());
            requisitionProduct.setRequisitionId(purchaseRequisition.getId());
            requisitionProductMapper.insert(requisitionProduct);
        });
        double productPrice = 0.00;

        List<RequisitionProduct> requisitionProducts = requisitionProductMapper.selectByRequisitionId(purchaseRequisition.getId(), null);
        for (RequisitionProduct requisitionProduct : requisitionProducts) {
            productPrice += requisitionProduct.getProductBuyPrice();
        }
        purchaseRequisition.setProductPrice(productPrice);
        purchaseMapper.updateById(purchaseRequisition);

        AddPageData addPageData = new AddPageData();
        addPageData.setStreamType(22);
        addPageData.setTitle(purchaseRequisition.getTitle());
        addPageData.setCorrelationId(purchaseRequisition.getId());
        addPageData.setWorkflowJson(purchaseRequisition.getWorkflowJsonList());
        addPageData.setAdminId(purchaseRequisition.getAdminId());
        addPageData.setExempt(purchaseRequisition.getExempt());
        return addPageData;
    }

    @Override
    public void updatePurchase(PurchaseRequisition purchaseRequisition) {
        PurchaseRequisition purchase = purchaseMapper.selectById(purchaseRequisition.getId());
        if (purchase != null){
            purchaseMapper.updateById(purchaseRequisition);
            if (purchaseRequisition.getRequisitionProductList() != null){
                QueryWrapper<RequisitionProduct> wrapper = new QueryWrapper<>();
                wrapper.lambda().eq(RequisitionProduct::getRequisitionId,purchase.getId());
                requisitionProductMapper.delete(wrapper);
                purchaseRequisition.getRequisitionProductList().forEach(requisitionProduct -> {
                    Product product = productMapper.selectById(requisitionProduct.getProductSpuId());
                    double BuyPrice = requisitionProduct.getPrice() * requisitionProduct.getProductBuyNum();
                    requisitionProduct.setProductBuyPrice(BuyPrice);
                    requisitionProduct.setUnitId(product.getProductUnitId());
                    requisitionProduct.setRequisitionId(purchaseRequisition.getId());
                    requisitionProductMapper.insert(requisitionProduct);
                });
            }
        }
    }

    @Override
    public PurchaseRequisition detailById(Integer id) {
        PurchaseRequisition purchaseRequisition = purchaseMapper.selectDetailById(id);
        List<RequisitionProduct> requisitionProducts = requisitionProductMapper.selectByRequisitionId(id, null);
        purchaseRequisition.setRequisitionProductList(requisitionProducts);
        return purchaseRequisition;
    }

    @Override
    public void auditPurchase(DoReminder doReminder) {
        //修改状态
        PurchaseRequisition purchaseRequisition = purchaseMapper.selectById(doReminder.getCorrlelationId());
        purchaseRequisition.setStatus(doReminder.getStatus());
        purchaseRequisition.setUpdateTime(DateUtil.date());
        purchaseRequisition.setRequisitionState(doReminder.getStatus());
        purchaseMapper.updateById(purchaseRequisition);
    }

    @Override
    public void deleteById(Integer id) {
        PurchaseRequisition purchaseRequisition = purchaseMapper.selectById(id);
        if (purchaseRequisition.getStatus() != 1 ){
            QueryWrapper<RequisitionProduct> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(RequisitionProduct::getRequisitionId,id);
            customerService.deleteThorough(23,id);
            requisitionProductMapper.delete(wrapper);
            purchaseMapper.deleteById(id);
        }
    }


    @Override
    public List<PurchaseRequisition> getListDetail(String ids, Integer generateState){
        ArrayList<PurchaseRequisition> list = new ArrayList<>();
        List<Integer> id = Stream.of(ids.split(",")).map(Integer::valueOf).collect(Collectors.toList());
        id.forEach( purchaseId -> {
            PurchaseRequisition purchaseRequisition = purchaseMapper.selectDetailById(purchaseId);
            //获取采购单code
            Procurement procured = procurementMapper.selectCodeByCG(purchaseRequisition.getId());
            if (procured != null){
                purchaseRequisition.setPurchaseCode(procured.getProcuredCode());
                purchaseRequisition.setProcurementCreateTime(procured.getCreateTime());
            }
            String operatorName = adminMapper.selectUsernameById(purchaseRequisition.getOperatorId());
            purchaseRequisition.setOperatorName(operatorName);
            List<RequisitionProduct> requisitionProducts = requisitionProductMapper.selectByRequisitionId(purchaseId,generateState);
            if (requisitionProducts != null){
                requisitionProducts.forEach(requisitionProduct -> {
                    Product product = productMapper.selectById(requisitionProduct.getProductSpuId());
                    requisitionProduct.setSpecificationName(product.getSpuSpecification());
//                    String financeUnitName = unitMapper.getFinanceUnitName(product.getFinanceUnitId());
//                    requisitionProduct.setFinanceUnitName(financeUnitName);
                });
            } else {
                requisitionProducts = new ArrayList<>();
            }
            purchaseRequisition.setRequisitionProductList(requisitionProducts);
            list.add(purchaseRequisition);
        });
        return list;
    }


    @Override
    public void cancel(String ids) {

        //删除采购单 和 采购物品单
        List<Integer> item = Stream.of(ids.split(",")).map(Integer::valueOf).collect(Collectors.toList());
        item.forEach( id -> {

            //删除采购物品单
            Procurement procurement = procurementMapper.selectOneByRequisitionProductId(id);
            if (procurement != null && procurement.getStatus() == 0){
                QueryWrapper<ProcurementProduct> wrapper = new QueryWrapper<>();
                wrapper.lambda().eq(ProcurementProduct::getProcurementId,procurement.getId());
                List<ProcurementProduct> procurementProducts = procurementProductMapper.selectList(wrapper);
                for (ProcurementProduct procurementProduct : procurementProducts) {
                    if (procurementProduct.getRequisitionProductId().equals(id)) {
                        procurementProductMapper.deleteById(procurementProduct);
                    }
                }
                wrapper.clear();
                wrapper.lambda().eq(ProcurementProduct::getProcurementId,procurement.getId());
                List<ProcurementProduct> cancelList = procurementProductMapper.selectList(wrapper);
                if (cancelList.size() == 0){
                    procurementMapper.deleteById(procurement);
                }

                RequisitionProduct requisitionProduct = requisitionProductMapper.selectById(id);
                requisitionProduct.setProductState(1);
                requisitionProductMapper.updateById(requisitionProduct);

                PurchaseRequisition purchaseRequisition = purchaseMapper.selectById(requisitionProduct.getRequisitionId());
                purchaseRequisition.setRequisitionState(0);
                purchaseMapper.updateById(purchaseRequisition);
            }

        });
    }

    @Override
    public Page<Product> productSpuList(Integer page, Integer limit, Integer categoryId, String search){
        Page<Product> specsPage = new Page<>(page, limit);
        Page<Product> productSpuPage = productMapper.selectListByItem(specsPage, categoryId, search);
        return productSpuPage;
    }

    @Override
    public void antiAudit(Integer correlationId) {
        QueryWrapper<PurchaseRequisition> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(PurchaseRequisition::getId,correlationId).eq(PurchaseRequisition::getStatus,1);
        PurchaseRequisition purchaseRequisition = purchaseMapper.selectOne(wrapper);
        purchaseRequisition.setStatus(0);
        purchaseMapper.updateById(purchaseRequisition);
    }
}
